// pages/calendar/calendar.js
const app = getApp();
const util = require('../../../utils/util.js')
let dayscount = 30;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    weekCover: true,
    dayCover: true,
    dayDate: {},
    weekData: [{
        week: 1,
        day: '一',
        time: {
          top: false,
          middle: false,
          bottom: true
        }
      },
      {
        week: 2,
        day: '二',
        time: {
          top: true,
          middle: false,
          bottom: false
        }
      },
      {
        week: 3,
        day: '三',
        time: {
          top: false,
          middle: false,
          bottom: false
        }
      },
      {
        week: 4,
        day: '四',
        time: {
          top: true,
          middle: true,
          bottom: false
        }
      },
      {
        week: 5,
        day: '五',
        time: {
          top: true,
          middle: false,
          bottom: true
        }
      },
      {
        week: 6,
        day: '六',
        time: {
          top: false,
          middle: false,
          bottom: false
        }
      },
      {
        week: 0,
        day: '日',
        time: {
          top: true,
          middle: true,
          bottom: false
        }
      }
    ],
    courseData: {},
    bottomTimeShow: [], // 选中哪个日期显示时间小栏
    choosePage: '',
    getChooseDate: [],
    loadBool: false,
    isJobCourse: null
  },

  dealDate: function(){
    // console.log(this.data.getChooseDate)
    let dates = this.data.dates
    // console.log(dates)
    dates.forEach(item =>{
      item.forEach(val => {
        this.data.getChooseDate.forEach(msg =>{ 
          if (new Date(val.date).getTime() == msg.studate){
            val.orderTime[util.formatDateDtate(msg.state)] = true
          }
        })
      })
    })
    this.setData({
      dates
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let passData = wx.getStorageSync('passData'),
      passStartDate = passData.startTime.split('-'),
      passEndDate = passData.endTime.split('-')

    let startDate = {
      year: passStartDate[0],
      month: passStartDate[1] - 1,
      day: passStartDate[2]
    };

    let endDate = {
      year: passEndDate[0],
      month: passEndDate[1] - 1,
      day: passEndDate[2]
    };
    
    let that = this
    // console.log('passData')
    // console.log(wx.getStorageSync('passData').classid)

    wx.request({
      url: app.globalData.baseUrl +'/calendars/gettimetable',
      // url: 'http://192.168.2.64:8080/calendars/gettimetable',
      method: 'POST',
      header: {
        "Content-Type": "application/json"
      },
      data: {
        "classid": wx.getStorageSync('passData').classid
      },
      success(res){
        let data = res.data.data.timetableList
        that.setData({
          getChooseDate: data
        })
        that.dealDate()
      }
    })
    
    
    intDate(this, startDate, endDate);

    this.setData({
      courseData: passData,
      isJobCourse: passData.isJobCourse
    })
  },

  toQuickChoice() {
    this.setData({
      weekCover: false
    })
    // this.selectComponent('#chooseFreeTime').getData()
  },
  quickChoice(eventDetail) {
    // console.log(eventDetail.detail);
    let dates = this.data.dates;
    let weekChoose = eventDetail.detail.weekDate;
    dates.forEach((date) => {
      date.map((el, index) => {
        weekChoose.map((el1, index1) => {
          if (el.week == el1.week) {
            el.orderTime = el1.time
          }
        })
      })
    })
    this.setData({
      dates: dates
    });
    // console.log(dates)
  },
  confirmFn(e) {
    // console.log('555')
    // console.log(e)
    let dates = this.data.dates,
      index = e.currentTarget.dataset.index,
      bottomTimeShow = this.data.bottomTimeShow,
      checkDay = e.currentTarget.dataset.checkDay
    if (!(checkDay.orderTime.top || checkDay.orderTime.middle || checkDay.orderTime.bottom)) return

    dates.forEach(val => {
      val.forEach(item => {
        if (item.date == checkDay.date) {
          item.showBorder = !item.showBorder
          bottomTimeShow.length = 0
          if (item.showBorder) {
            bottomTimeShow[index] = checkDay.orderTime
          }
        } else {
          item.showBorder = false
        }
      })
    })

    this.setData({
      dates: dates,
      bottomTimeShow: bottomTimeShow
    });
  },
  btnSubmitFn(e) {
    let that = this
    const query = wx.createSelectorQuery();
    query.select('.period-wrapper').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function (res) {
      // console.log(res)
      wx.getSystemInfo({
        success(msg){
          let windowHeight = msg.windowHeight;
          if (res[0].height > windowHeight && ((res[0].height - res[1].scrollTop) != windowHeight)){
            wx.showToast({
              title: '请浏览完课表~',
              icon: 'none',
              duration: 2000
            })
            return
          }

          that.setData({
            loadBool: true
          })
          // console.log(that.data.courseData.formalclassid)
          wx.showModal({
            title: '',
            content: '确认排班计划后，上课时间将以该计划为准',
            cancelText: '取消',
            showCancel: true,
            confirmText: '确认',
            confirmColor: '#2A8EFF',
            success(res) {
              // 点击取消的时候 return 不做任何事
              if (res.cancel) {
                that.setData({
                  loadBool: false
                })
                return
              }
              util.sendForm(e.detail.formId, '8yXiZLs675d1hmlWll80Vkqsz72dVhcMYRmzRWPRja4', '3', wx.getStorageSync('passData').courseId, wx.getStorageSync('passData').packId)
              wx.request({
                url: app.globalData.baseUrl + '/calendars/confirmTimeTable',
                method: 'POST',
                header: {
                  "Content-Type": "application/json"
                },
                data: {
                  "stuId": wx.getStorageSync('userInfo').cluesOrStuId,
                  "formalClassId": that.data.courseData.formalclassid,
                },
                success(res) {

                }
              })


              that.setData({
                loadBool: false
              })

              wx.reLaunch({
                url: '/pages/detail/waitGrade/waitGrade?showTextIndex=1&showBtn=1'
              })
            }
          })

        }
      })
      
    })
  }
});

function intDate(self, fromDay, toDay) {
  let platform;//手机操作系统
  wx.getSystemInfo({
    success: function (res) {
      // console.log(res.platform)
      platform = res.platform;
    }
  })
  let nowYear = fromDay.year,
    nowMonth = fromDay.month,
    today = fromDay.day;
  let endDate = new Date(toDay.year, toDay.month, toDay.day),
    endYM = new Date(endDate.getFullYear(), endDate.getMonth());
  let dates = [];
  for (let i = nowMonth; new Date(nowYear, i) <= endYM; i++) {
    let item = [];
    let monthDays = new Date(nowYear, i + 1, 0).getDate(); //获取该月天数  +1
    for (let j = 1; j <= monthDays; j++) {
      let _year = new Date(nowYear, i).getFullYear(),
        _month = new Date(nowYear, i).getMonth() + 1, //获取该月月份 +1
        _date = `${_year}-${_month}-${j}`
      let day = _year + '/' + _month + '/' + j,
        datTimeStamp = new Date(_year + ',' + _month + ',' + j).getTime()  // 得到当天的时间戳
      if (platform == 'ios') {
        _date = `${_year}/${_month}/${j}`
      }
      item.push({
        week: new Date(_date).getDay(),
        orderTime: {
          top: false,
          middle: false,
          bottom: false
        },
        showBorder: false,
        date: day.toString(),
        choosed: false
      });
    }
    dates.push(item);
  }
  let startDay = `${nowYear}/${nowMonth + 1}/${today}`,
    endDay = `${endDate.getFullYear()}/${endDate.getMonth() + 1}/${endDate.getDate()}`;
  self.setData({
    dates,
    startDay,
    endDay
  })
}